package com.remoter.serialize.kryo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;
import com.remoter.api.extension.annotation.ExtensionName;
import com.remoter.api.serialize.ISerialization;

@ExtensionName("kryo")
public class KryoSerialization implements ISerialization{
	
	private final KryoPool pool;
	
	public KryoSerialization(){
		this.pool = KryoPoolFactory.getInstance();
	}
	
	@Override
	public void serialize(Object data,OutputStream outputStream)throws IOException {
		Kryo kryo = this.pool.borrow();
		try{
			Output out = new Output(outputStream);
	        kryo.writeClassAndObject(out,data);
	        out.close();
	        outputStream.close();
		}finally{
			this.pool.release(kryo);
		}
	}

	@Override
	public Object deserialize(InputStream input)throws IOException {
		Kryo kryo = this.pool.borrow();
		try{
			Input in = new Input(input);
			Object result = kryo.readClassAndObject(in);
	        in.close();
	        input.close();
	        return result;
		}finally{
			this.pool.release(kryo);
		}
	}
	
}